<?php ob_start() ?>

<!-- 显示成功消息 -->
    <?php if(session()->has('message')): ?>
        <div class="alert alert-success">
            <?php echo session()->getFlashdata('message'); ?>
        </div>
    <?php endif; ?>

    <!-- 显示错误消息 -->
    <?php if(session()->has('error')): ?>
        <div class="alert alert-danger">
            <?php echo session()->getFlashdata('error'); ?>
        </div>
    <?php endif; ?>

<div class="grid grid-cols-12 gap-6 relative">
    <!-- 左侧内容区 - 十二分之十 -->
    <div class="col-span-12 lg:col-span-10">
        <?= $mainContent ?>
    </div>
    
    <!-- 右侧推荐链接区和关键词编辑区 - 十二分之二 -->
    <div class="col-span-12 lg:col-span-2">
        <!-- 推荐研学基地链接区域 -->
        <div class="fixed top-24 right-24 w-[calc(16.666667%-1.5rem)] bg-white rounded-xl shadow-lg p-4 mb-4">
            <h3 class="text-lg font-bold text-gray-800 mb-3">推荐链接：</h3>
            <ul id="link-list" class="space-y-2">
                <?php if (!empty($linkData)): ?>

                    <?php foreach ($linkData as $link): ?>
                        <li class="link-item flex justify-between items-center">
                            <a href="<?= $link['link_url'] ?>" data-link-url="<?= $link['link_txt'] ?>" class="text-primary hover:underline flex items-center" onclick="recordClick(<?= $link['to_page_id'] ?>);">
                                <?= $link['locationOrder'] ?> <?= $link['link_txt'] ?>
                            </a>
                            <?php if (1 == $editLinkStatus): ?>
                            <button class="delete-link bg-transparent border-none text-red-500 hover:text-red-700" data-from-page-id="<?= $link['from_page_id'] ?>" data-to-page-id="<?= $link['to_page_id'] ?>">
                                <i class="fa-solid fa-xmark"></i>
                            </button>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                <?php else: ?>
                    <li>暂无链接</li>
                <?php endif; ?>
            </ul>

            <?php if (1 == $editLinkStatus): ?>
            <h3 class="text-sm font-bold text-gray-800 mb-3">设置推荐链接</h3>
            <form action="<?= site_url('/yanxue/set_link') ?>" method="post" id="link-form">
                <select name="link" id="link" class="border border-gray-300 rounded p-2 w-full mb-2">
                    <option value="">请选择</option>
                    <?php if (!empty($allLinks)): ?>
                        <?php foreach ($allLinks as $link): ?>
                            <option value="<?= $link['introUrl'] ?>" data-linktxt="<?= $link['linkTxt'] ?>" data-topageid="<?= $link['toPageId'] ?>" ><?= $link['locationOrder'] ?> <?= $link['linkTxt'] ?></option>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </select>
                <input type="hidden" name="linkTxt" id="linkTxt">
                <input type="hidden" name="toPageId" id="toPageId">
                <input type="hidden" name="page_id" value="<?= $location['id'] ?>">
                <button type="submit" class="bg-primary text-white py-2 px-4 rounded hover:bg-primary-dark" id="add-link-button">增加链接</button>
            </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>

    // document.getElementById('keyword-form').addEventListener('submit', function(event) {
    //     var keyword = document.getElementById('keyword').value;
    //     if (keyword.length !== 2) {
    //         alert('关键词长度必须为2个字');
    //         event.preventDefault();
    //     }
    // });

    document.getElementById('link-form').addEventListener('submit', function(event) {
        var link = document.getElementById('link').value;

        var toPageId = document.getElementById('toPageId').value;
        var linkTxt = document.getElementById('linkTxt').value;
        if (link === '' || toPageId === '0' || linkTxt === '') {
            alert('请选择有效的链接和目标页面，并确保链接文本不为空');
            event.preventDefault();
        }
    });

    document.addEventListener('DOMContentLoaded', function() {

        document.getElementById('link').dispatchEvent(new Event('change'));
        document.getElementById('link').addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            setTimeout(() => {
                document.getElementById('linkTxt').value = selectedOption.dataset.linktxt;
                document.getElementById('toPageId').value = selectedOption.dataset.topageid;
            }, 100); // 延迟 100 毫秒
            // document.getElementById('linkTxt').value = selectedOption.dataset.linktxt;
            // document.getElementById('toPageId').value = selectedOption.dataset.topageid;
        });


        // var deleteButtons = document.querySelectorAll('.delete-keyword');
        // console.log('deleteButtons 数量:', deleteButtons.length); // 关键词按钮数量
        // deleteButtons.forEach(function(button) {
        //     button.addEventListener('click', handleDeleteKeyword);
        // });
        // const disabledLink = document.getElementById('disabledLink');
        // disabledLink.addEventListener('click', function(e) {
        //     e.preventDefault(); // 阻止默认行为
        //     const linkUrl = this.dataset.linkUrl;
        //     alert(`这个链接会带你去 【${linkUrl}研学基地介绍页】，但当前不可用`);
        // });
        var deleteLinkButtons = document.querySelectorAll('.delete-link');
        // console.log('deleteButtons 数量:', deleteLinkButtons.length); // 链接按钮数量
        deleteLinkButtons.forEach(function(button) {
            button.addEventListener('click', handleDeleteLink);
        });

        // 页面加载时检查关键词数量
        // checkKeywordCount();
        checkLinkCount();
    });

    function handleDeleteKeyword() {
        const listItem = this.closest('li');
        const keyword = this.dataset.keyword;
        const pageId = this.dataset.pageId;

        if (confirm('确定要删除该关键词吗？')) {
            const formData = new FormData();
            formData.append('keyword', keyword);
            formData.append('page_id', pageId);

            fetch('<?= site_url('/yanxue/remove_keyword') ?>', {
                method: 'POST',
                body: formData
            })
           .then(response => response.text())
           .then(data => {
                listItem.remove();
                alert('关键词删除成功');
                // 删除关键词后检查数量
                checkKeywordCount();
            })
           .catch(error => {
                alert('关键词删除失败');
            });
        }
    }

    function handleDeleteLink() {
        const listItem = this.closest('li');
        const toPageId = this.dataset.toPageId;
        const fromPageId = this.dataset.fromPageId;
            console.log(this.dataset);
            console.log(toPageId);
            console.log(fromPageId);

        if (confirm('确定要删除该链接吗？')) {
            const formData = new FormData();
            formData.append('toPageId', toPageId);
            formData.append('fromPageId', fromPageId);
            console.log(formData);
            fetch('<?= site_url('/yanxue/remove_link') ?>', {
                method: 'POST',
                body: formData
            })
           .then(response => response.text())
           .then(data => {
                listItem.remove();
                alert('链接删除成功');
                // 删除链接后检查数量
                checkLinkCount();
            })
           .catch(error => {
                alert('链接删除失败');
            });
        }
    }

    function checkKeywordCount() {
        var keywordList = document.getElementById('keyword-list');
        var keywordItems = keywordList.querySelectorAll('li');
        var addButton = document.getElementById('add-keyword-button');

        if (keywordItems.length >= 6) {
            addButton.disabled = true;
            addButton.classList.add('disabled-button');
        } else {
            addButton.disabled = false;
            addButton.classList.remove('disabled-button');
        }
    }

    function checkLinkCount() {
        var linkList = document.getElementById('link-list');
        var linkItems = linkList.querySelectorAll('li');
        var addButton = document.getElementById('add-link-button');

        if (linkItems.length >= 5) {
            addButton.disabled = true;
            addButton.classList.add('disabled-button');
        } else {
            addButton.disabled = false;
            addButton.classList.remove('disabled-button');
        }
    }

    function recordClick(page_id) {
        fetch('<?= site_url('/record-click-activity/') ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ page_id: page_id })
        })
       .then(response => response.json())
       .then(data => console.log(data));
    }
</script>

<style>
    .keyword-item {
        background-color: #e0f2fe; /* 淡蓝色背景 */
        border-radius: 0.375rem; /* 圆角 */
        padding: 0.25rem 0.5rem; /* 内边距 */
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .link-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    /* 定义禁用按钮的样式 */
    .disabled-button {
        background-color: #cccccc; /* 灰色背景 */
        cursor: not-allowed; /* 禁用鼠标指针 */
    }
    .disabled-button:hover {
        background-color: #cccccc; /* 鼠标悬停时保持灰色 */
    }
</style>

<?php $content = ob_get_clean() ?>

<?= view('layouts/base', ['content' => $content]) ?>